<?php


namespace App\Http\Controllers\Admin;


use App\Events\OrderRefundFinished;
use App\Model\Refund;
use App\Service\Pay\PayFactory;
use App\Tool\Json;
use App\Tool\Notify;
use App\Tool\PayType;

class RefundController extends AuthCheckController
{

    /**
     * 退款列表
     * Create by Peter
     * 2019/12/30 11:46:59
     * Email:904801074@qq.com
     * @return array
     */
    function refund_list(){

        $list=Refund::with('user')->orderBy('id','desc');


        return paginate($list,request()->input('p'));
    }


    /**
     * 请求退款接口
     * Create by Peter
     * 2019/12/30 11:48:16
     * Email:904801074@qq.com
     */
    function do_refund(){

        try {

            \DB::beginTransaction();

//            \DB::connection()->enableQueryLog();

            $id = request()->input('id');

            $info = Refund::with('order_transaction')
                ->with('order')
                ->with('user')
                ->where('id', $id)->where('status', 1)->first();

            if(!$info) return Json::code(2,'找不到退款id或者状态不对');

            $pay_type = $info->pay_type;

            $pay = PayFactory::getPay(PayType::getPayType($pay_type));

            $data = [
                $info->order_transaction->transaction_id,
                uniqid() . '_' . $id . '_' . $pay_type,
                $info->order_transaction->total_fee * 100,
                $info->refund_price * 100,
                Notify::getRefundNotifyUrlByPayType(PayType::getPayType($pay_type))
            ];

            $res = $pay->refund(...$data);

            if($res['result_code']=='FAIL') throw new \Exception($res['err_code_des']);

            Refund::where('id',$id)->where('status',1)
                ->update(['status'=>2]);

//            $logs = \DB::getQueryLog();

            \DB::commit();

            event(new OrderRefundFinished($info->order,1,$info->user));

            return Json::code(1,'success',$res);

        }catch (\Exception $exception){

            \DB::rollBack();


            return Json::code(2,$exception->getMessage());

        }

    }

    /**
     * 拒绝退款
     * Create by Peter
     * 2019/12/31 13:59:51
     * Email:904801074@qq.com
     */
    function refuse(){

        $id = request()->input('id');

        $info = Refund::with('order_transaction')
            ->with('order')
            ->with('user')
            ->where('id', $id)->where('status', 1)->first();

        $info->fill(['status'=>4])->save();

        event(new OrderRefundFinished($info->order,2,$info->user));

        return Json::code(1,'success');

    }

}
